package com.example.demo.demos.web;

import com.example.demo.bean.Order;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.REUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class test_shopfiy {

    private static Logger logger = LoggerFactory.getLogger(test_shopfiy.class);

    public static List<Order> getOrderList(String accessToken,String requestURL) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            URL url = new URL(requestURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("X-Shopify-Access-Token", accessToken);
            String jsonInput = "{\n" +
                    "  \"query\": \"query { orders(first: 250) { edges { node { id lineItems(first:10){edges {node{id}}} } } pageInfo { hasPreviousPage hasNextPage startCursor endCursor } } }\"\n" +
                    "}";
            connection.setDoOutput(true);
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInput.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }
            int responseCode = connection.getResponseCode();
            logger.info("POST Response Code : " + responseCode);
            StringBuilder response = null;
            if (responseCode == HttpURLConnection.HTTP_OK) { // 成功响应
                try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    String inputLine;
                    response = new StringBuilder();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                }
                logger.info(response.toString());
                String responseData = response.toString();
                JsonNode responseJson = objectMapper.readTree(responseData);
                System.out.println(responseJson.get("data"));
                JsonNode t = objectMapper.readTree(responseJson.get("data").toString());
                System.out.println(t.get("orders"));

                JsonNode pageInfo = t.get("orders").get("pageInfo");
                System.out.println(pageInfo.toString());

                JsonNode edges = t.get("orders").get("edges");
                System.out.println(edges);

            } else {
                logger.error("POST request not worked.");
            }
        }catch (IOException e){
            throw new IOException("异常");
        }
        return null;
    }

    public static void main(String[] args) throws IOException {
        // 设置系统属性以使用代理
        System.setProperty("http.proxyHost", "192.168.12.13");
        System.setProperty("http.proxyPort", "7890");
        System.setProperty("https.proxyHost", "192.168.12.13");
        System.setProperty("https.proxyPort", "7890");

        String accessToken = "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"; // 替换为你的Shopify访问令牌
        String requestURL = "https://a770be-2.myshopify.com/admin/api/2024-10/graphql.json";
        getOrderList(accessToken,requestURL);


    }


    /***
     *    try {
     *             URL url = new URL(requestURL);
     *             HttpURLConnection connection = (HttpURLConnection) url.openConnection();
     *             connection.setRequestMethod("POST");
     *             connection.setRequestProperty("Content-Type", "application/json");
     *             connection.setRequestProperty("X-Shopify-Access-Token", accessToken);
     *             //分页查询
     *             String jsonInput = "{\n" +
     *                     "  \"query\": \"query { orders(first: 10) { edges { node { id } cursor } pageInfo { hasPreviousPage hasNextPage startCursor endCursor } } }\"\n" +
     *                     "}";
     * //            String jsonInput = "{\n" +
     * //                    "  \"query\": \"query { orders(first: 10) { edges { node { id } } } }\"\n" +
     * //                    "}";
     * ////            gid://shopify/Order/6209547600203     gid://shopify/Order/6215409566027
     * //            String jsonInput = "{\n" +
     * //                    "  ordersCount {\n" +
     * //                    "    " +
     * //                    "  }\n" +
     * //                    "}";
     *
     * //            String jsonInput = "{\n" +
     * //                    "  \"query\": \"query { order1: order(id: \\\"gid://shopify/Order/6209547600203\\\") { name, id,processedAt,phone} order2: order(id: \\\"gid://shopify/Order/6215409566027\\\") { name,id,processedAt,phone } }\"\n" +
     * //                    "}";
     *
     * //            String jsonInput = "{" +
     * //                    "\"query\": \"mutation StorefrontAccessTokenCreate($input: StorefrontAccessTokenInput!) { storefrontAccessTokenCreate(input: $input) { userErrors { field message } shop { id } storefrontAccessToken { accessScopes { handle } accessToken title } } }\"," +
     * //                    "\"variables\": {" +
     * //                    "  \"input\": {" +
     * //                    "    \"title\": \"New Storefront Access Token\"" +
     * //                    "  }" +
     * //                    "}" +
     * //                    "}";
     *             connection.setDoOutput(true);
     *             try (OutputStream os = connection.getOutputStream()) {
     *                 byte[] input = jsonInput.getBytes(StandardCharsets.UTF_8);
     *                 os.write(input, 0, input.length);
     *             }
     *             int responseCode = connection.getResponseCode();
     *             System.out.println("POST Response Code :: " + responseCode);
     *             if (responseCode == HttpURLConnection.HTTP_OK) { // 成功响应
     *                 try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
     *                     String inputLine;
     *                     StringBuilder response = new StringBuilder();
     *                     while ((inputLine = in.readLine()) != null) {
     *                         response.append(inputLine);
     *                     }
     *                     System.out.println(response.toString());
     *                 }
     *             } else {
     *                 System.out.println("POST request not worked.");
     *             }
     *
     *         } catch (Exception e) {
     *             e.printStackTrace();
     *         }
     */

}
